package com.exartisan.molisasurvey;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.ar.network.NetworkUtility;
import com.ar.network.RestConnector;
import com.ar.network.StupidParametersBuilder;
import com.exartisan.bean.User;
import com.exartisan.utils.ResponseParser;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends BaseActivity {
	
	 private static final String TAG = "DialogActivity";
	    private static final int DLG_EXAMPLE1 = 0;
	    private static final int TEXT_ID = 0;

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private LoginButton fbLoginBtn;
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 uiHelper = new UiLifecycleHelper(this, callback);
		    uiHelper.onCreate(savedInstanceState);
		    /*if (Session.getActiveSession() !=null) 
		    	if (Session.getActiveSession().isOpened()) 
		    		Session.getActiveSession().closeAndClearTokenInformation();*/
		    fbLoginBtn = (LoginButton) findViewById(R.id.authButton);
			fbLoginBtn.setReadPermissions(Arrays.asList("basic_info", "email"));
			try {
				PackageInfo info;
				info = getPackageManager().getPackageInfo(
				        "com.exartisan.molisasurvey", 
				        PackageManager.GET_SIGNATURES);
				 for (Signature signature : info.signatures) {
			            MessageDigest md = MessageDigest.getInstance("SHA");
			            md.update(signature.toByteArray());
			            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			            }
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
	}


	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		/*if (mAuthTask != null) {
			return;
		}*/

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			if (NetworkUtility.checkNetworkState(getApplicationContext())){
				showProgress(true);
			RestConnector.post("", StupidParametersBuilder.BuildParams(StupidParametersBuilder.BuildLoginData(mEmail, mPassword, NetworkUtility.NORMAL)), new AsyncHttpResponseHandler(){
				
				public void onSuccess(int arg0, String response) {
					super.onSuccess(arg0, response);
					Log.d("login_response", response);
					if(ResponseParser.checkSuccess(response)){
						User user = new User();
						user = getUser();
						user.setEmail(mEmail);
						user.setUser_id(ResponseParser.getUserID(response));
						String areaName = ResponseParser.getAreaName(response);
						if (areaName.equals("null")) areaName = "Thành đoàn Hà Nội";
						user.setYouthunion(areaName);
						/*RestConnector.post("", StupidParametersBuilder.BuildParams(StupidParametersBuilder.BuildLoadSurveyData(getUser().getUser_id())), new AsyncHttpResponseHandler(){
							
							public void onSuccess(int arg0, String response) {
								Log.d("zz", response);
								showProgress(false);
								super.onSuccess(arg0, response);
								if (ResponseParser.checkSuccess(response)){
									Intent intent = new Intent(getApplicationContext(), ContestActivity.class);
									intent.putExtra("surveyList", response);
									startActivity(intent);
									finish();
								}
								else 
									NetworkUtility.showDialog(getCurrentActivity(), "Error", ResponseParser.getErrorMessage(response));
							}
							
							@Override
							public void onFailure(Throwable arg0, String arg1) {
								showProgress(false);
								super.onFailure(arg0, arg1);
								NetworkUtility.showTimeOutDialog(getCurrentActivity());
							}
							
						});*/
						Intent intent = new Intent(getApplicationContext(), ContestActivity.class);
						startActivity(intent);
						finish();
					} else {
						showProgress(false);
						NetworkUtility.showDialog(getCurrentActivity(), "Thông báo", ResponseParser.getErrorMessage(response));
					}
					
				}
				
				@Override
				public void onFailure(Throwable arg0, String arg1) {
					super.onFailure(arg0, arg1);
					showProgress(false);
					NetworkUtility.showTimeOutDialog(getCurrentActivity());
				}
			}); 
			} else
				NetworkUtility.showNoNetworkDialog(getCurrentActivity());
			
			//mAuthTask = new UserLoginTask();
			//mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_login);
	}

	@Override
	protected void initViews() {
		
	}

	@Override
	protected void initVariables() {
		
	}

	@Override
	protected void initActions() {
		
		if (getUser().getUser_id() != null) {
			Intent intent = new Intent(getApplicationContext(), ContestActivity.class);
			finish();
			startActivity(intent);
		}
		
		// Set up the login form.
				mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
				mEmailView = (EditText) findViewById(R.id.email);
				mEmailView.setText(mEmail);

				mPasswordView = (EditText) findViewById(R.id.password);
				mPasswordView
						.setOnEditorActionListener(new TextView.OnEditorActionListener() {
							@Override
							public boolean onEditorAction(TextView textView, int id,
									KeyEvent keyEvent) {
								if (id == R.id.login || id == EditorInfo.IME_NULL) {
									attemptLogin();
									return true;
								}
								return false;
							}
						});

				mLoginFormView = findViewById(R.id.login_form);
				mLoginStatusView = findViewById(R.id.login_status);
				mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

				findViewById(R.id.sign_in_button).setOnClickListener(
						new View.OnClickListener() {
							@Override
							public void onClick(View view) {
								attemptLogin();
							}
						});
	}
	
	@Override
	protected void setUpActionBar() {
		getSupportActionBar().hide();
	}
	
	public void onClickRegister(View view){
		Intent intent = new Intent(this, InputInfoActivity.class);
		startActivity(intent);
	}
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    if (state.isOpened()) {
	    	/*Intent intent = new Intent(this, ContestActivity.class);
			startActivity(intent);*/
	    	Request.newMeRequest(session, new GraphUserCallback() {
				
				public void onCompleted(GraphUser user, Response response) {
					final String email = (String)(user.asMap().get("email"));
					
					mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
					if (NetworkUtility.checkNetworkState(getApplicationContext())){
						showProgress(true);
					RestConnector.post("", StupidParametersBuilder.BuildParams(StupidParametersBuilder.BuildLoginData(email, "", NetworkUtility.FACEBOOK)), new AsyncHttpResponseHandler(){
						
						public void onSuccess(int arg0, String response) {
							super.onSuccess(arg0, response);
							Log.d("login_response", response);
							if(ResponseParser.checkSuccess(response)){
								getUser().setUser_id(ResponseParser.getUserID(response));
								getUser().setEmail(email);
								String areaName = ResponseParser.getAreaName(response);
								if (areaName == null) areaName = "Thành đoàn Hà Nội";
								getUser().setYouthunion(areaName);
								/*RestConnector.post("", StupidParametersBuilder.BuildParams(StupidParametersBuilder.BuildLoadSurveyData(getUser().getUser_id())), new AsyncHttpResponseHandler(){
									
									public void onSuccess(int arg0, String response) {
										Log.d("zz", response);
										showProgress(false);
										super.onSuccess(arg0, response);
										if (ResponseParser.checkSuccess(response)){
											Intent intent = new Intent(getApplicationContext(), ContestActivity.class);
											intent.putExtra("surveyList", response);
											Session.getActiveSession().closeAndClearTokenInformation();
											startActivity(intent);
											finish();
										}
										else 
											NetworkUtility.showDialog(getCurrentActivity(), "Error", ResponseParser.getErrorMessage(response));
									}
									
									@Override
									public void onFailure(Throwable arg0, String arg1) {
										showProgress(false);
										super.onFailure(arg0, arg1);
										NetworkUtility.showTimeOutDialog(getCurrentActivity());
									}
									
								});*/
								Intent intent = new Intent(getApplicationContext(), ContestActivity.class);
								startActivity(intent);
								finish();
							} else {
								showProgress(false);
								NetworkUtility.showDialog(getCurrentActivity(), "Thông báo", ResponseParser.getErrorMessage(response));
							}
							
						}
						
						@Override
						public void onFailure(Throwable arg0, String arg1) {
							super.onFailure(arg0, arg1);
							showProgress(false);
							NetworkUtility.showTimeOutDialog(getCurrentActivity());
						}
					}); 
					} else
						NetworkUtility.showNoNetworkDialog(getCurrentActivity());

					
				}
			}).executeAsync();
	    } else if (state.isClosed()) {
	    	
	    }
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    
	 // For scenarios where the main activity is launched and user
	    // session is not null, the session state change notification
	    // may not be triggered. Trigger it if it's open/closed.
	  /*  Session session = Session.getActiveSession();
	    if (session != null &&
	           (session.isOpened() || session.isClosed()) ) {
	        onSessionStateChange(session, session.getState(), null);
	    }*/
	    
	    uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_MENU) {
	        openOptionsMenu();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		final com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.login, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		showDialog(DLG_EXAMPLE1);
		return true;
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
 
        switch (id) {
            case DLG_EXAMPLE1:
                return createExampleDialog();
            default:
                return null;
        }
    }
	
	private Dialog createExampleDialog() {
		 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Set IP");
        builder.setMessage("Nhập địa chỉ IP:");
 
         // Use an EditText view to get user input.
         final EditText input = new EditText(this);
         String first = NetworkUtility.API_URL;
         first = first.substring(7, 19);
         input.setText(first);
         input.setId(TEXT_ID);
         builder.setView(input);
 
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString().trim();
                NetworkUtility.API_URL = "http://"+value+":8081/Services/Index";
                return;
            }
        });
 
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
 
        return builder.create();
    }
}


